<template>
  <div class="my-project-layout">
    <div class="my-project-addProject" @click="handleOpenProjectDialog">
      <img :src="newProject" alt="">
      <div>创建工程</div>
    </div>
    <div class="my-list-header">
      <div class="my-list-header_title">
        工程信息
      </div>
      <div class="my-list-header_mange">
        <el-input size="small" placeholder="搜索" v-model="query.name" @keyup.enter.native="getList" clearable
                  @change="getList"></el-input>
      </div>
    </div>
    <el-row :gutter="10">
      <el-col v-loading="projectLoading" :xs="24" :sm="12" :md="6" :lg="6" :xl="6" v-for="project in projectList">
        <dv-border-box7 class="my-list" :key="project.project_id">
          <div class="my-list_content">
            <div class="my-list-body">
              <div class="my-list-body-img">
                <img :src="project.thumb" alt="">
                <div class="my-list-body-edit">
                  <div class="my-list-body-edit-btn">
                    <div>
                      <el-button size="small" class="btn_edit cursor_point" @click="handlePagesByProject(project)">
                        进入工程
                      </el-button>
                    </div>
                    <div class="btn_edit_icon">
                      <el-tooltip class="toolTipHover" effect="dark" content="工程复制" placement="bottom" trigger="hover">
                        <i class="iconfont icon-copy_link cursor_point" :key="project.project_id"
                           @click="handleProjectCopy(project)"/>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="工程导出" placement="bottom" trigger="hover">
                        <i class="iconfont icon-export cursor_point" :key="project.project_id"></i>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="工程删除" placement="bottom" trigger="hover">
                        <i class="iconfont icon-delete cursor_point" :key="project.project_id"
                           @click="handleDelProject(project.project_id)"></i>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="my-list-body-edit-icon">
                    <el-tooltip class="toolTipHover" effect="dark" content="工程发布" placement="bottom" trigger="hover">
                      <i class="iconfont icon-publish cursor_point" :key="project.project_id"></i>
                    </el-tooltip>
                    <el-tooltip class="toolTipHover" effect="dark" content="工程预览" placement="bottom"
                                trigger="hover">
                      <i class="iconfont icon-preview cursor_point" :key="project.project_id"></i>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
            <div class="my-list-footer">
              <div v-if="editFlag && selectId===project.project_id">
                <el-input v-model="projectModel.name" @blur="handleEditProjectName" size="mini"
                          placeholder="输入名称"
                          @keydown.enter="$event.target.blur()"></el-input>
              </div>
              <div v-else>
                {{ project.name }}
                <span class="iconfont icon-edit edit-btn" @click="editProjectName(project)"></span>
              </div>
            </div>
          </div>
        </dv-border-box7>
      </el-col>
    </el-row>
    <el-drawer
        v-model="drawerActive"
        title="新增专案"
        size="24%"
        direction="rtl">
      <el-form
          :model="projectModel"
          :rules="rules"
          ref="projectFormRef"
          label-placement="left"
          label-align="right"
          :label-width="80"
          size="small">
        <el-form-item label="专案名称:" path="name">
          <el-input placeholder="专案名称" v-model="projectModel.name"/>
        </el-form-item>
        <el-form-item label="备注:" path="remark">
          <el-input placeholder="备注"
                    v-model="projectModel.remark"
                    type="textarea"
                    :autosize="{
                          minRows: 3,
                          maxRows: 5
                        }"/>
        </el-form-item>
        <el-upload
            class="avatar-uploader"
            :action="requestUrl" :headers="{Authorization:token}"
            :show-file-list="false"
            :on-success="handlePicUploadFinish"
            @before-upload="beforePicUpload">
          <img v-if="projectModel.thumb" :src="projectModel.thumb" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <span class="iconfont icon-Add"></span>
          </el-icon>
        </el-upload>
      </el-form>
      <div class="footer-modal">
        <el-button type="primary" size="small" @click="handleAddProjectAction" class="base-primary-btn m_lr_10">确认
        </el-button>
        <el-button size="small" @click="drawerActive = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import newProject from "../../assets/png/new-project.png";
import { addProject, copyProject, deleteProject, editProjectNameById, getProjectList } from "../../service/project";
import DvBorderBox7 from "../../components/datav/border-box7/src/main.vue";
import { getToken } from "../../utils/storage";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  name: "my-project-list",
  components: {
    DvBorderBox7,
  },
  setup(prop, ctx) {
    const query = ref({
      name: "",
    });
    const projectLoading = ref(false);
    const formLoading = ref(false);
    const projectFormRef = ref(null);
    const drawerActive = ref(false);
    const projectList = ref([]);
    const projectName = ref("");
    const editFlag = ref(false);
    const router = useRouter();
    const selectId = ref(null);
    const requestUrl = ref();
    const token = ref("");
    const projectModel = ref({
      name: "",
      remark: "",
      thumb: ""
    });
    const handleOpenProjectDialog = () => {
      projectModel.value = {
        name: "",
        remark: "",
        thumb: ""
      };
      drawerActive.value = true;
    };
    const handleAddProjectAction = () => {
      formLoading.value = true;
      projectFormRef.value.validate((errors) => {
        if (!errors) {
          addProject(projectModel.value).then(() => {
            ElMessage({
              type: "success",
              message: "新增项目成功"
            });
            drawerActive.value = false;
            getList();
            formLoading.value = false;
          }).catch(() => {
            formLoading.value = false;
          });
        } else {
          formLoading.value = false;
          console.log(errors);
        }
      });
    };
    const getList = () => {
      projectLoading.value = true;
      getProjectList(query.value).then(res => {
        projectList.value = res.data.result;
        projectLoading.value = false;
      }).catch(() => {
        projectLoading.value = false;
      });
    };
    const handlePagesByProject = (project) => {
      const project_id = project.project_id;
      ctx.emit("changeCurrent", "page");
      router.push({ path: "/project/page", query: { project_id } });
    };
    const handleProjectCopy = (project) => {
      projectLoading.value = true;
      copyProject({ project_id: project.project_id }).then(res => {
        getList();
      }).catch(() => {
        projectLoading.value = false;
      });
    };
    const editProjectName = (project) => {
      projectModel.value = {
        name: "",
        remark: "",
        thumb: ""
      };
      projectModel.value = project;
      selectId.value = project.project_id;
      editFlag.value = true;
    };
    const handleEditProjectName = () => {
      if (!projectModel.value.thumb) {
        ElMessage.error("请输入项目名称");
        return;
      }
      editProjectNameById(projectModel.value).then(res => {
        ElMessage({
          type: "success",
          message: "修改项目成功"
        });
        getList();
        editFlag.value = false;
      }).catch(err => {
        ElMessage.error(err.message);
      });
    };
    const handleDelProject = (project_id) => {
      ElMessageBox.confirm(
          "你确定删除当前项目",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        projectLoading.value = true;
        deleteProject({ project_id }).then(() => {
          ElMessage({
            type: "success",
            message: "删除项目成功"
          });
          getList();
        }).catch(err => {
          projectLoading.value = false;
          ElMessage.error(err.message);
        });
      });
    };
    const handlePicUploadFinish = (res, file) => {
      if (res.code === 0) {
        const { result, path } = res.data;
        projectModel.value.thumb = import.meta.env.VITE_APP_REQUEST + path;
      }
    };
    const beforePicUpload = (file) => {
      if (!["image/jpeg", "image/png", "image/jpg"].includes(file.type)) {
        ElMessage.error("只能上传png/jpg格式的文件，请重新上传");
        return false;
      }
      return true;
    };
    onMounted(() => {
      token.value = "Bearer " + getToken();
      requestUrl.value = import.meta.env.VITE_APP_REQUEST + "/v1/dataPicture/upload";
      getList();
    });
    return {
      formLoading,
      query,
      projectLoading,
      token,
      requestUrl,
      newProject,
      drawerActive,
      projectFormRef,
      projectList,
      projectName,
      editFlag,
      selectId,
      projectModel,
      rules: ref({
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入专案名称"
        }
      }),
      handleAddProjectAction,
      handleOpenProjectDialog,
      handlePagesByProject,
      handleEditProjectName,
      editProjectName,
      handleDelProject,
      getList,
      handlePicUploadFinish,
      beforePicUpload,
      handleProjectCopy
    };
  }
});
</script>

<style lang="less" scoped>
@import "./../../style/page/my-project.less";

.upload-csv {
  font-size: 44px;
}
</style>
